import { Col, Modal, Row, Spin } from "antd";
import { Button, Card, Checkbox, DatePicker, List, Stepper, WingBlank } from 'antd-mobile';
import { Brief } from "antd-mobile/lib/list/ListItem";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { decodeUrlParam, PAGE_TYPE, ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
const Item = List.Item;
const AgreeItem = Checkbox.AgreeItem;

export const payAmountMap = {
    'subsidy': '补贴账户抵扣',
    'recharg': 'APP储值账户抵扣',
    'real': '账户实付'
};

/**
 * 组件：提交订单首页状态
 */
export interface CleanSubmitOrderViewState extends ReactViewState {
    getTime?: any;
    current_user_info?: any;
    distribution?: any;
    buy_list?: any;
    /** 请求支付信息接口返回的信息 */
    pay_mount_result?: any;
    /** 购买产品列表json信息字符串 */
    buy_list_json_str_b64?: string;
    modal_time_open: boolean;
    appointment_time?: any;
    is_agree: boolean;
    loading: boolean;
    modal_aggre_open: boolean;
}

/**
 * 组件：提交订单首页
 * 描述
 */
export class CleanSubmitOrderView extends ReactView<CleanSubmitOrderViewControl, CleanSubmitOrderViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            distribution: [{ label: "送货上门", value: 1 }, { label: "幸福院就餐", value: 2 }, { label: "幸福院自取", value: 3 }],
            getTime: [{ label: "半小时后", value: 1 }, { label: "一小时后", value: 2 }, { label: "一个半小时后", value: 3 }],
            buy_list: [],
            current_user_info: undefined,
            modal_time_open: false,
            appointment_time: undefined,
            is_agree: false,
            modal_aggre_open: false,
            loading: true
        };
    }

    getUrlParams = () => {
        let buy_list_json_str_b64 = this.props.match!.params.key;
        let buy_list_json = JSON.parse(decodeUrlParam(buy_list_json_str_b64));
        return buy_list_json;
    }

    Changedistribution = (e: any) => {
        console.log(11);
    }
    goPayment = () => {
        // 创建订单，同时插入唯一商品id，供订单列表查询
        let buy_list_json = this.getUrlParams();
        if (buy_list_json.page_type = PAGE_TYPE.BUY) {
            AppServiceUtility.comfirm_order_service.create_product_order!(
                buy_list_json.page_info.map((e: any, i: number) => {
                    return {
                        'service_product_id': e.id,
                        // 'name': e.abstract,
                        'buy_type': '自费',
                        'count': e.num,
                        'amout': e.amount_total,
                        'appointment_time': this.state.appointment_time
                    };
                }),
                0
            );
        }
        this.props.history!.push(ROUTE_PATH.payment + '/' + this.state.buy_list_json_str_b64);
    }

    componentWillMount() {
        const user = IntelligentElderlyCareAppStorage.getCurrentUser();
        this.setState({
            current_user_info: user
        });
    }

    componentDidMount() {
        this.setState({
            buy_list_json_str_b64: this.props.match!.params.key
        });

        let buy_list_json = this.getUrlParams();
        this.getPayMountResult(buy_list_json);
    }

    getPayMountResult = (buy_list_json: any) => {
        const user = IntelligentElderlyCareAppStorage.getCurrentUser();

        AppServiceUtility.app_pay_service.receive_pay_info!(
            {
                payer_id: user.id,
                info: buy_list_json.page_info
            }
        )!.then((data: any) => {
            console.log("服务详情", data);
            this.setState({
                loading: false,
                pay_mount_result: data
            });
        });
        console.log(buy_list_json);
        this.setState({
            buy_list: buy_list_json.page_info,
        });
    }

    getServer = () => {
        //     AppServiceUtility.service_detail_service.get_server_list!({ id: '105df5ac-0301-11ea-9fd1-005056882303' }, 1, 1)!
        //     .then((data: any) => {
        //         if (data.result.length > 0) {
        //             const result = data.result[0];
        //             this.setState({ server_info: result });
        //             if (result.follow_list.length > 0) {
        //                 this.setState({ follow: true });
        //             }
        //         }
        //     })
        //     .catch((err) => {
        //         console.info(err);
        // });
    }

    getZeroTime = () => {
        return new Date(new Date().toLocaleDateString());
    }

    goAddress = () => {
        this.props.history!.push(ROUTE_PATH.address);
    }

    getPriceEleList = () => {
        let list = [];
        let data: Object = this.state.pay_mount_result;
        for (const k in data) {
            if (data.hasOwnProperty(k)) {
                const e = data[k];
                list.push(
                    <List key={k}>
                        <Item extra={'￥' + (e['amount'])} multipleLine={true} wrap={true}>
                            <Brief style={{ textOverflow: 'unset' }}>
                                {payAmountMap[k]}
                                {
                                    e['balance'] !== undefined ?
                                        `（余额￥：${e['balance']}）`
                                        :
                                        ''
                                }
                            </Brief>
                        </Item>
                    </List>
                );
            }
        }
        // TODO：暂时增加可用券
        list.push(
            <List key={'可用券'}>
                <Item extra={'￥ 0'}>可用券</Item>
            </List>
        );
        return list;
    }

    onBuyItemNumChange = (id: string, e: any) => {
        console.log(id, e);
        let buy_list = this.changeNumAndPriceById(id, e);
        let buy_list_json = this.getUrlParams();
        buy_list_json.page_info = buy_list;
        this.getPayMountResult(buy_list_json);
        this.setState({ buy_list });
    }

    changeNumAndPriceById = (id: string, num: number) => {
        const { buy_list } = this.state;

        for (const k in buy_list) {
            if (buy_list.hasOwnProperty(k)) {
                let e = buy_list[k];
                const onePrice = e.price / e.num;
                e.num = num;
                e.price = e.num * onePrice;
                e.amount_total = e.price;
                return buy_list;
            }
        }
        return undefined;
    }

    render() {
        const { current_user_info } = this.state;
        // const address = current_user_info.adress;
        const service_aggrement = '';
        // current_user_info.personnel_info.service_aggrement;
        setMainFormTitle("确认订单");
        return (
            <Spin spinning={this.state.loading}>
                {
                    this.state.pay_mount_result ?
                        (
                            <>
                                <div className="main-content">
                                    <List>
                                        <Item arrow={"horizontal"}>{current_user_info.name}</Item>
                                        {/* <Item extra={<Button type="ghost" inline={true} size="small" >修改</Button>}>
                                            {address ? address : '请选择服务地址'}
                                        </Item> */}
                                    </List>
                                    <List style={{ marginTop: '1em', marginBottom: "1em" }}>
                                        {this.state.buy_list.map((item: any, index: any) => {
                                            return (
                                                <>
                                                    <Card className='list-content' key={index}>
                                                        <Row type='flex' justify='center'>
                                                            <Col className='list-col' span={12}><img src={item.picture_collection} style={{ height: '72pt', width: '130px' }} /></Col>
                                                            <Col span={12} >
                                                                <Row><strong>{item.abstract}</strong></Row>
                                                                <Row >
                                                                    ￥{item.price}
                                                                </Row>
                                                            </Col>
                                                        </Row>
                                                    </Card>
                                                    <Item extra={<Stepper min={1} showNumber={true} defaultValue={item.num} onChange={(e) => { this.onBuyItemNumChange(item.id, e); }} />}>购买数量</Item>
                                                </>
                                            );
                                        })}
                                    </List>
                                    {this.state.pay_mount_result ?
                                        this.getPriceEleList()
                                        :
                                        <></>
                                    }
                                    {
                                        this.getUrlParams().appointment_data ? <List>
                                            <Item extra={this.getUrlParams().appointment_data}>预约时间</Item>
                                        </List> : ''
                                    }
                                </div>
                                <div>
                                    {/* <div className="main-content">
                                <List className="address-input">
                                    <Item arrow="horizontal" onClick={this.goAddress}>
                                        选择收货地址
                                    </Item>
                                </List>
                                <WhiteSpace size="sm" />
                                <List>
                                    <Item>
                                        订单详情
                                    </Item>
                                </List>
                                {this.state.buy_list.map((item: any, index: any) => {
                                    return (<Card className='list-content' key={index}>
                                        <Row type='flex' justify='center'>
                                            <Col className='list-col' span={12}><img src={item.picture_collection} style={{ height: '72pt', width: '130px' }} /></Col>
                                            <Col span={12} >
                                                <Row><strong>{item.abstract}</strong></Row>
                                                <Row style={{ paddingRight: '10px' }}>
                                                    <span className="list-col-span">￥{item.amount_total}</span>
                                                </Row>
                                                <Row>
                                                    <Col span={12}>x{item.num}</Col>
                                                </Row>
                                            </Col>
                                        </Row>
                                    </Card>);
                                })}
                                <WhiteSpace size="sm" />
                                {this.state.pay_mount_result ?
                                    this.getPriceEleList()
                                    :
                                    <></>
                                }
                                {
                                    this.getUrlParams().appointment_data ? <List>
                                        <Item extra={this.getUrlParams().appointment_data}>预约时间</Item>
                                    </List> : ''
                                }
                                <WhiteSpace size="sm" />
                                <List>
                                    <Item arrow="horizontal" onClick={(e) => { this.props.history!.push(ROUTE_PATH.remarks); }}>备注</Item>
                                </List>
                                <WhiteSpace size="lg" />
                                <WhiteSpace size="lg" />
                                <WhiteSpace size="lg" />
                            </div> */}
                                    <div className="submit-btn">
                                        <Row>
                                            <Col span={12}>
                                                <Button className={"btn-amount"} style={{ pointerEvents: "none" }}  >{'￥' + (this.state.pay_mount_result['real']['amount'])}
                                                </Button>
                                            </Col>
                                            <Col span={12}>
                                                <Button type={"primary"} style={{ borderRadius: 0 }} onClick={() => this.setState({ modal_time_open: true })}>立即支付</Button>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>
                                <Modal
                                    // popup={true}
                                    visible={this.state.modal_time_open}
                                    // onClose={this.onClose('modal2')}
                                    // afterClose={() => { alert('afterClose'); }}
                                    closable={false}
                                    // footer={[{ text: 'Ok', onPress: () => { console.log('ok'); } }]}
                                    okText={"确定"}
                                    title={"时间预约"}
                                    onOk={() => this.setState({ modal_time_open: false, modal_aggre_open: true })}
                                    onCancel={() => this.setState({ modal_time_open: false })}
                                    cancelText={"取消"}

                                // footer={[{ text: '确定', onPress: () => { console.log('ok'); } }, { text: '取消', onPress: () => { console.log('ok'); } }]}
                                >
                                    <DatePicker
                                        value={this.state.appointment_time ? this.state.appointment_time : this.getZeroTime()}
                                        onChange={date => this.setState({ appointment_time: date })}
                                        minuteStep={60}
                                    >
                                        <List.Item arrow="horizontal">请选择</List.Item>
                                    </DatePicker>
                                </Modal>
                                <Modal
                                    // popup={true}
                                    visible={this.state.modal_aggre_open}
                                    // onClose={this.onClose('modal2')}
                                    // afterClose={() => { alert('afterClose'); }}
                                    closable={false}
                                    // footer={[{ text: 'Ok', onPress: () => { console.log('ok'); } }]}
                                    okButtonProps={{ disabled: !this.state.is_agree }}
                                    okText={"同意"}
                                    title={"居家服务协议协议"}
                                    onOk={this.goPayment}
                                    onCancel={() => this.setState({ modal_aggre_open: false })}
                                    cancelText={"不同意"}

                                // footer={[{ text: '确定', onPress: () => { console.log('ok'); } }, { text: '取消', onPress: () => { console.log('ok'); } }]}
                                >
                                    <WingBlank>
                                        {service_aggrement ?
                                            service_aggrement :
                                            "无"
                                        }
                                    </WingBlank>
                                    <AgreeItem onChange={(e: any) => { this.setState({ is_agree: e.target.checked }); }}>
                                        同意
                            </AgreeItem>
                                </Modal>
                            </>
                        )
                        :
                        <></>
                }
            </Spin>
        );
    }
}

/**
 * 控件：提交订单首页控制器
 * 描述
 */
@addon('CleanSubmitOrderView', '提交订单首页', '描述')
@reactControl(CleanSubmitOrderView, true)
export class CleanSubmitOrderViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}